﻿using Dapper;
using MediatR;
using MySql.Data.MySqlClient;
using SCM.API.Read.Application.Command;
using SCM.API.Read.Application.Command.PurchaseRefund;
using SCM.Domain;
using SCM.ErrorCode;
using SCM.Infrastructure.Interface;
using System.Text;

namespace SCM.API.Read.Application.Handler.PurchaseRefund
{
    public class GetPurchaseRefundHandler : IRequestHandler<GetPurchaseRefundCommand, APIResult<PurchaseRefundModel>>
    {
       ILogger<GetPurchaseRefundHandler> logger;
        IDatabaseContext db;

        public GetPurchaseRefundHandler(ILogger<GetPurchaseRefundHandler> logger, IDatabaseContext db)
        {
            this.logger = logger;
            this.db = db;
        }

        public async Task<APIResult<PurchaseRefundModel>> Handle(GetPurchaseRefundCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new APIPaging<PurchaseRefundModel>();

                var countSql = new StringBuilder();
                var sqlBuilder = new StringBuilder();

                sqlBuilder.Append(@"SELECT 
                                        id,
                                        refundNum,
                                        productName,
                                        productId,
                                        productSpecs,
                                        unitId,
                                        price,
                                        num,
                                        total,
                                        vendorId,
                                        vendorName,
                                        purchaseId,
                                        state,
                                        madeTime,
                                        invoiceType,
                                        invoiceState,  
                                        madeName,
                                        createTime,
                                        contact,
                                        phone,
                                        createName,
                                        `desc`,
                                        updateName,
                                        isDel
                                FROM PurchaseRefundModel WHERE isDel=false ");

                countSql.Append("SELECT COUNT(id) FROM PurchaseRefundModel WHERE isDel=false ");

                var parameters = new DynamicParameters();

                if (!string.IsNullOrEmpty(request.PurchaseId))
                {
                    sqlBuilder.Append("AND PurchaseId = @PurchaseId ");
                    parameters.Add("PurchaseId", request.PurchaseId);
                    countSql.Append("AND PurchaseId = @PurchaseId ");
                }
                if (!string.IsNullOrEmpty(request.ProductName))
                {
                    sqlBuilder.Append("AND ProductName LIKE @ProductName ");
                    parameters.Add("ProductName", $"%{request.ProductName}%");
                    countSql.Append("AND ProductName LIKE @ProductName ");
                }
                if (!string.IsNullOrEmpty(request.RefundNum))
                {
                    sqlBuilder.Append("AND RefundNum = @RefundNum ");
                    parameters.Add("RefundNum", request.RefundNum);
                    countSql.Append("AND RefundNum = @RefundNum ");
                }
                if (request.State != null)
                {
                    sqlBuilder.Append("AND State = @State ");
                    parameters.Add("State", request.State);
                    countSql.Append("AND State = @State ");
                }

                sqlBuilder.Append(@" ORDER BY CreateTime DESC LIMIT @PageSize OFFSET @Offset ");
                parameters.Add("PageSize", request.PageSize);
                parameters.Add("Offset", (request.PageIndex - 1) * request.PageSize);

               

                var data = await db.DapperConnection.QueryAsync<PurchaseRefundModel>(sqlBuilder.ToString(), parameters);
                var total = await db.DapperConnection.ExecuteScalarAsync<int>(countSql.ToString(), parameters);

                result.Msg = "显示成功";
                result.Code = APIEnum.Success;
                result.items = data.ToList();
                result.totalCount = total;
                result.totalPage = (int)Math.Ceiling((double)total / request.PageSize);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message, "查询采购退货信息失败");
                throw;
            }
        }
    }
}
